#include <assert.h>

#include <osg/Transform>

#include "SetRotateCenterHandler.h"
#include "CmdManager.h"
#include "SelectHandler3D.h"
#include "OSGNodeMask.h"
#include "QtOSGWidget.h"
#include "ViewerExt.h"
#include "Manipulator/RotateManipulator.h"
#include "INode.h"

SetRotateCenterHandler::SetRotateCenterHandler()
{
}

void SetRotateCenterHandler::input(const QVariant& data, const QString& rawInput, CommandSource cs)
{
	auto selector = qobject_cast<SelectHandler3D*>(getSelectHandler());
	if (!selector)
	{
		emit finished();
		return;
	}

	if (data.type() == QVariant::Bool)
	{
		bool esc = !data.toBool();
		if (esc)
		{
			selector->clearSelection();
			clearInput();
			emit finished();
			return;
		}
	}


	if (status() == 0)
	{
		selector->clearSelection();
		selector->beginSelect(~NoPickMask, 1);
		prompt(1, tr("选择对象:"));
		return;
	}

	if (status() == 1)
	{
		if (selector->done())
		{
			auto selector = qobject_cast<SelectHandler3D*>(getSelectHandler());
			if (!selector)
				return;
			auto nodes = selector->selectionSet();
			if (nodes.size() >= 1)
			{
				std::shared_ptr<INode> node = *nodes.begin();
				auto osgNode = node->getRep3D();
				auto sphere = osgNode->getBound();
				auto center = sphere.center();
				auto pathList = osgNode->getParentalNodePaths();
				if (pathList.size() >= 1)
				{
					auto matrix = osg::computeLocalToWorld(pathList[0]);
					center = center * matrix;
					auto widget3D = getWidget();
					auto viewer = dynamic_cast<ViewerExt*>(widget3D->getViewer());
					if (viewer)
					{
						auto manipulator = viewer->getCameraManipulator();
						auto rotateManipulator = dynamic_cast<RotateManipulator*>(manipulator);
						if (rotateManipulator)
							rotateManipulator->setPointAsRotateCenter(center);
					}
				}
			}
			emit finished();
			return;
		}
	}
}

